﻿/*
    Copyright (c) 2009 Chris Umbel

    Permission is hereby granted, free of charge, to any person obtaining a 
	copy of this software and associated documentation files (the "Software"), 
	to deal in the Software without restriction, including without limitation 
	the rights to use, copy, modify, merge, publish, distribute, sublicense, 
	and/or sell copies of the Software, and to permit persons to whom the Software 
	is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all 
	copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
	FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
	COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
	IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace DLRHostService
{
    public partial class ServiceHost : ServiceBase
    {
        private ScriptEngine _engine;
        private ScriptScope _scope;
        private ScriptSource _source;
        private ScriptRuntime _runtime;
        private Thread _hostThread;
        public bool IsRunning { get; set; }
        
        public ServiceHost()
        {
            InitializeComponent();

            try
            {
                /* create the DLR */
                ScriptRuntimeSetup setup = new ScriptRuntimeSetup();
                /* include a few languages i.e. ruby, python, etc... */
                setup.LanguageSetups.Add(IronPython.Hosting.Python.CreateLanguageSetup(null));
                setup.LanguageSetups.Add(IronRuby.Ruby.CreateRubySetup());
                _runtime = new ScriptRuntime(setup);

                /* create the engine for the specified language type, i.e. python, ruby, etc... */
                _engine = _runtime.GetEngine(ConfigurationManager.AppSettings["ServiceLanguage"]);
                _scope = _engine.CreateScope();

                /* tell the engine where to load other code from */
                _engine.SetSearchPaths(new string[] { AppDomain.CurrentDomain.BaseDirectory });
            } 
            catch(Exception ex)
            {
                Logger.Write(string.Format("Failed to create runtime: {0}", ex.ToString()), "Error");
                throw ex;
            }
        }

        private void RunHost()
        {
            Logger.Write("Running script");

            try
            {
                /* run the script */
                _source.Execute(_scope);
                _engine.Operations.Invoke(_scope.GetVariable("run_service"));
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("DLR Error {0}", ex.ToString()), "Error");
            }
        }

        protected override void OnStart(string[] args)
        {
            Logger.Write("Service starting");
            this.IsRunning = true;

            try
            {
                /* load script from disk */
                _source = _engine.CreateScriptSourceFromFile(
                    ConfigurationManager.AppSettings["ServiceScript"]);
                /* give the script a handle to this object */
                _scope.SetVariable("service_host", this);
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Failed to start script {0}", ex.ToString()), "Error");
            }

            /* fire off a worker thread to host the script */
            _hostThread = new Thread(new ThreadStart(RunHost));
            _hostThread.Start();

            Logger.Write("Service started");
        }

        protected override void OnStop()
        {
            Logger.Write("Service stopping");

            this.IsRunning = false;

            /* instruct the script we're hosting to shut down */
            try
            {
                _engine.Operations.Invoke(_scope.GetVariable("stop_service"));
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Failed to cleanly stop script {0}", ex.ToString()), "Error");
            }

            /* wait for DLR worker thread to stop */
            if(!(_hostThread.Join(20000)))
            {
                /* if the script fails to shutdown within the timeout force it */
                _engine.Runtime.Shutdown();
                Logger.Write("Script shutdown timed out, shutdown forced", "Warning");
            }

            Logger.Write("Service stopped");
        }
    }
}
